package com.bolt.auth.security.admin.biz.sys.service;


import com.bolt.auth.admin.api.sys.dto.DictDetailDTO;
import com.bolt.auth.admin.api.sys.dto.converter.DictDetailConverter;
import com.bolt.auth.admin.api.sys.entity.DictDetailEntity;
import com.bolt.auth.admin.api.sys.entity.DictEntity;
import com.bolt.auth.security.admin.biz.sys.repository.DictDetailRepository;
import com.bolt.support.base.service.BaseService;
import com.bolt.support.spring.jpa.jpql.Clauses;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Auto Generate Javadoc
 *
 * @author 日期:2020-10-23 17:32:40
 *         数据字典详情
 **/
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class DictDetailService extends BaseService <DictDetailEntity, Long> {

    @Autowired
    private DictDetailRepository detailRepository;

    @Override
    protected BasicJpaRepository <DictDetailEntity, Long> getRepository() {
        return detailRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(DictDetailDTO dto) {
        DictDetailEntity entity = DictDetailConverter.toEntity(dto);
        save(entity);
    }

    public List <DictDetailDTO> findByDictId(Long dictId) {
        return this.jpaQueryFactory.select(DictDetailDTO.class,
                Clauses.of(DictDetailEntity::getValue),
                Clauses.of(DictDetailEntity::getLabel))
                .from(Clauses.of(DictDetailEntity.class))
                .where(Clauses.of().eq(Clauses.of(DictDetailEntity::getDictId), dictId))
                .fetch();
    }

    public List<DictDetailDTO> queryByDictName(String dictName){
        return jpaQueryFactory.select(DictDetailDTO.class,
                Clauses.of(DictDetailEntity::getValue),
                Clauses.of(DictDetailEntity::getLabel))
                .from(Clauses.of(DictDetailEntity.class))
                .innerJoin(Clauses.of(DictEntity.class))
                .on(Clauses.of(DictDetailEntity::getDictId), Clauses.of(DictEntity::getId))
                .where(Clauses.of().eq(Clauses.of(DictEntity::getName), dictName))
                .orderBy(Clauses.of(DictDetailEntity::getDictSort))
                .fetch();
    }
}
